// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database({
  env: 'gtss-2b1812'
})
exports.main = async(event, context) => {
  try {
    if (event.type == 'stu') {
      const isHas = await db.collection('Student').where({
        _id: event._id
      }).count()
      if (isHas.total == 0) {
        await db.collection('Student').add({
          data: {
            _id: event._id,
            stuName: event.name,
            stuClass: event.stuClass,
            stuDept: event.dept,
            stuSex: event.sex,
            stuPhone: event.phone,
            stuPas: '123456',
            stuState: 0,
            stuTopicId: '',
            stuTopicName: ''
          }
        })
      } else {
        return {
          result: 2
        }
      }
    } else if (event.type == 'tea') {
      const isHas = await db.collection('Teacher').where({
        _id: event._id
      }).count()
      if (isHas.total == 0) {
        await db.collection('Teacher').add({
          data: {
            _id: event._id,
            teaName: event.name,
            teaDept: event.dept,
            teaSex: event.sex,
            teaPhone: event.phone,
            teaPas: '123456',
            teaState: 0,
            teaPost: event.teaPost
          }
        })
      } else {
        return {
          result: 2
        }
      }
    }
    return {
      result: 1
    }
  } catch (e) {
    return {
      result: 3
    }
  }
}